package cn.yunhe.controller;

import cn.yunhe.beans.Item;
import cn.yunhe.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;

/**
 * @author herbert
 * @date 2021/2/2
 */
@Controller
@RequestMapping("/item")
public class ItemController {


    @Autowired
    ItemService itemService;


    /**
     * 查询产品列表
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/queryList.do")
    public String queryUsers(ModelMap modelMap) {
        List<Item> itemList = itemService.queryItemList();
        modelMap.addAttribute("itemList", itemList);
        return "item-list";
    }

    /**
     * 添加产品
     *
     * @param item
     * @param multipartFile
     * @param request
     * @return
     * @throws IOException
     * @throws IOException
     * @throws ParseException
     */
    @RequestMapping("/insertItem.do")
    public String insertItem(Item item,
                             @RequestParam(value = "file", required = false) MultipartFile multipartFile, HttpServletRequest request) throws IOException, IOException, ParseException {
        String fieldName = multipartFile.getOriginalFilename();
        //获取文件的后缀名
        int index = fieldName.lastIndexOf(".");
        String suffix = fieldName.substring(index);
        //使用UUID生成一个随机数作为新的名字
        String uuidName = UUID.randomUUID().toString().replace("-", "");
        String uploadName = uuidName + suffix;
        //将上传的文件写入到指定的地址中
        String realPath = request.getServletContext().getRealPath("/static/pic");
        multipartFile.transferTo(new File(realPath, uploadName));
        //将图片的地址写入到数据库
        item.setPic(uploadName);
        itemService.insertItem(item);
        return "redirect:/item/queryList.do";
    }


    /**
     * 根据id查询产品
     *
     * @param modelMap
     * @param id
     * @return
     */
    @RequestMapping("/queryItemById.do")
    public String queryItemById(ModelMap modelMap, Integer id) {
//         * 原生的写法应该是以HttpServletRequest request
//         * String id = request.getParameter("id");
        Item item = itemService.queryItemById(id);
        modelMap.addAttribute("item", item);
        return "item-edit";
    }

    /**
     * 更新用户信息
     *
     * @param item
     * @return
     */
    @RequestMapping("/updateItem.do")
    public String updateItem(Item item,
                             @RequestParam(value = "ItemPic", required = false) MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        try {
            String fieldName = multipartFile.getOriginalFilename();
            //获取文件的后缀名
            int index = fieldName.lastIndexOf(".");
            String suffix = fieldName.substring(index);
            //使用UUID生成一个随机数作为新的名字
            String uuidName = UUID.randomUUID().toString().replace("-", "");
            String uploadName = uuidName + suffix;
            //将上传的文件写入到指定的地址中
            String realPath = request.getServletContext().getRealPath("/static/pic");
            multipartFile.transferTo(new File(realPath, uploadName));
            item.setPic(uploadName);
        }catch (Exception e){
            //这个try catch是为了在没有修改图片的情况下执行字段的修改，只需要finally，不需要catch
        }finally {
            itemService.updateItem(item);
            return "redirect:/item/queryList.do";
        }
    }


    /**
     * 删除个别用户
     *
     * @param id
     * @param response
     * @param request
     * @return
     */
    @RequestMapping("/deleteItem.do")
    public String deleteItem(Integer id, HttpServletResponse response, HttpServletRequest request) {
        Item item = itemService.queryItemById(id);
        String fileName = item.getPic();
        String realPath = request.getServletContext().getRealPath("/static/pic/"+fileName);
        File file = new File(realPath);
        file.delete();
        itemService.deleteItem(id);
        return "redirect:/item/queryList.do";
    }

    /**
     * 多项删除
     *
     * @param ids
     * @param response
     * @param request
     * @return
     */
    @RequestMapping("/deleteAll.do")
    public String deleteAll(Integer[] ids, HttpServletResponse response, HttpServletRequest request) {
        for (int id : ids) {
            Item item = itemService.queryItemById(id);
            String fileName = item.getPic();
            String realPath = request.getServletContext().getRealPath("/static/pic/"+fileName);
            File file = new File(realPath);
            file.delete();
        }
        itemService.deleteAll(ids);
        return "redirect:/item/queryList.do";
    }


    @RequestMapping("/queryItemLike.do")
    public String queryItemLike(String itemName, ModelMap modelMap) {
        List<Item> queryList = itemService.queryItemLike(itemName);
        modelMap.addAttribute("queryList", queryList);
        return "itemQueryResult";
    }


}
